import json
from datetime import datetime

from django.core.paginator import Paginator
from django.db.models import Q
from django.http import JsonResponse

from lapi_app.models.bug_model.bug import Project, Bug_menu, Bug
from lapi_app.view.user_view.token_check import access_token


def project_list(request):
    try:
        data = json.loads(request.body)
        size_page = data["size_page"]
        current_pages = data["current_page"]
        if not access_token(data["user_id"]):
            return JsonResponse({
                "code": 1001,
                "message": "登录失效，请重新登录"
            })
        pro = Project.objects.filter(project_name__icontains=data["project_name"])
        project_total = len(pro)
        result = []
        for i in pro:
            pro_dict = {
                "id": i.id,
                "project_name": i.project_name,
                "project_describe": i.project_describe,
                "create_time": datetime.strftime(i.create_time, "%Y-%m-%d %H:%M:%S"),
                "update_time": datetime.strftime(i.update_time, "%Y-%m-%d %H:%M:%S"),
                "username": i.user.username
            }
            result.append(pro_dict)
        p = Paginator(result, size_page)
        page1 = p.page(current_pages)
        current_page = page1.object_list
        return JsonResponse({
            "code": 200,
            "content": current_page,
            "project_total": project_total,
            "size_page": size_page,
            "current_page": current_pages
        })
    except Exception as e:
        return JsonResponse({
            "code": 100,
            "message": str(e)
        })


def add_project(request):
    try:
        data = json.loads(request.body)
        if not access_token(data["user_id"]):
            return JsonResponse({
                "code": 1001,
                "message": "登录失效，请重新登录"
            })
        project_name = data["project_name"]
        project_describe = data["project_describe"]
        if project_name == "":
            return JsonResponse({
                "code": 100,
                "message": "项目名称不可为空"
            })
        if Project.objects.filter(project_name=project_name).count() >= 1:
            return JsonResponse({
                "code": 100,
                "message": "项目名称已存在，请重新输入"
            })
        else:
            pro = Project.objects.create(project_name=project_name, project_describe=project_describe,
                                         user_id=data["user_id"])
            Bug_menu.objects.create(label="根目录", pid=0, type=0, m_user_id=data["user_id"], project_id=pro.id)
            return JsonResponse({
                "code": 200,
                "message": "项目创建成功"
            })
    except Exception as e:
        return JsonResponse({
            "code": 100,
            "message": str(e)
        })


def edit_project(request):
    try:
        data = json.loads(request.body)
        if not access_token(data["user_id"]):
            return JsonResponse({
                "code": 1001,
                "message": "登录失效，请重新登录"
            })
        project_id = data["id"]
        project_name = data["project_name"]
        project_describe = data["project_describe"]
        if project_name == "" or project_id is None:
            return JsonResponse({
                "code": 100,
                "message": "必要参数不可为空"
            })
        if Project.objects.filter(~Q(id=project_id), project_name=project_name).count() >= 1:
            return JsonResponse({
                "code": 100,
                "message": "项目名称已存在，请重新输入"
            })
        else:
            Project.objects.filter(id=project_id).update(project_name=project_name, project_describe=project_describe,
                                                         user_id=data["user_id"])
            return JsonResponse ({
                "code": 200,
                "message": "编辑成功"
            })
    except Exception as e:
        return JsonResponse({
            "code": 100,
            "message": str(e)
        })


def del_project(request):
    try:
        data = json.loads(request.body)
        if not access_token(data["user_id"]):
            return JsonResponse({
                "code": 1001,
                "message": "登录失效，请重新登录"
            })
        if data["id"] is None or Project.objects.filter(id=data["id"]).count() < 0:
            return JsonResponse({
                "code": 100,
                "message": "该项目不存在"
            })
        else:
            Project.objects.filter(id=data["id"]).delete()
            return JsonResponse({
                "code": 200,
                "message": "删除成功"
            })
    except Exception as e:
        return JsonResponse({
            "code": 100,
            "message": str(e)
        })


def project_data(request):
    try:
        pro = Project.objects.all()
        result = []
        for i in pro:
            pro_dict = {
                "value": i.id,
                "label": i.project_name
            }
            result.append(pro_dict)
        return JsonResponse({
            "code": 200,
            "content": result,
            "message": "获取列表成功"
        })
    except Exception as e:
        return JsonResponse({
            "code": 100,
            "message": str(e)
        })


def add_edit_menu(request):
    data = json.loads(request.body)
    label = data["label"]
    t = data["type"]
    u = data["user_id"]
    if label == '' or data["id"] == '' or t == '' or u == '':
        return JsonResponse({'code': 100, 'message': "参数不能为空"})
    else:
        if data["action"] == "add":
            if Bug_menu.objects.filter(label=label).count() > 1:
                return JsonResponse({'code': 101, 'message': "名称已存在，请重新输入"})
            elif t == 1 or t == '1':
                menu = Bug_menu.objects.create(label=label, pid=data["id"], type=t, m_user_id=u, project_id=data["project_id"])
                return JsonResponse(
                    {'code': 200, 'message': "添加成功", "data": {"id": menu.id, "type": t, "label": label, "pid": data["id"], "project_prd": data["project_prd"]}})
            elif t == 2 or t == '2':
                menu = Bug_menu.objects.create(label=label, pid=data["id"], type=t, m_user_id=u, project_id=data["project_id"], project_prd=data["project_prd"])
                return JsonResponse(
                    {'code': 200, 'message': "添加成功",
                     "data": {"id": menu.id, "type": t, "label": label, "pid": data["id"]}})
        elif Bug_menu.objects.filter(label=label).count() > 1:
            return JsonResponse({'code': 101, 'message': "名称已存在，请重新输入"})
        else:
            if t == 2 or t == '2':
                Bug_menu.objects.filter(id=data["id"]).update(label=label, project_prd=data["project_prd"], update_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                return JsonResponse({'code': 200, 'message': "重命名成功", "id": data["id"], "label": label, "project_prd": data["project_prd"]})
            else:
                Bug_menu.objects.filter(id=data["id"]).update(label=label, update_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                return JsonResponse({'code': 200, 'message': "重命名成功", "id": data["id"], "label": label})


def del_menu(request):
    try:
        body = json.loads(request.body)
        id = body["id"]
        menu = Bug_menu.objects.get(id=id)
        if menu.type == 1:
            if Bug_menu.objects.filter(pid=id).count() > 0:
                return JsonResponse({
                    "code": 100,
                    "message": "该文件夹下存在其他模块，请先删除模块"
                })
            else:
                menu.delete()
                return JsonResponse({
                    "code": 200,
                    "message": "删除成功"
                })
        elif menu.type == 2:
            menu.delete()
            Bug.objects.filter(id=id).delete()
            return JsonResponse({
                "code": 200,
                "message": "删除成功"
            })
    except Exception as e:
        return JsonResponse({
            "code": 100,
            "message": str(e)
        })
